<template>
	<view class="order-container">
		<view v-if="orders.length === 0" class="empty-state">
			<text>暂无订单</text>
		</view>
		<view v-else class="order-list">
			<view v-for="order in orders" :key="order.id" class="order-item">
				<view class="order-header">
					<text class="order-id">订单号：{{ order.id }}</text>
					<text :class="['order-status', getStatusStyle(order.status)]">{{ getStatusText(order.status) }}</text>
				</view>
				<view class="order-content">
					<view v-for="item in order.items" :key="item.productId" class="order-product">
						<image :src="item.image" mode="aspectFill" class="product-image"></image>
						<view class="product-info">
							<text class="product-name">{{ item.name }}</text>
							<text class="product-price">{{ formatPrice(item.price) }}</text>
							<text class="product-quantity">x{{ item.quantity }}</text>
						</view>
					</view>
				</view>
				<view class="order-footer">
					<text class="order-time">{{ formatDate(order.orderTime) }}</text>
					<text class="total-amount">总计：{{ formatPrice(order.totalAmount) }}</text>
					<view class="order-actions">
						<button v-if="showActionButton(order)" class="action-button" @tap="handleActionButtonClick(order)">{{ getActionButtonText(order) }}</button>
						<button class="action-button delete" @tap="deleteOrder(order.id)">删除订单</button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			orders: [],
			userInfo: null
		}
	},
	onLoad() {
		this.loadUserInfo()
		this.loadOrders()
	},
	onShow() {
		this.loadUserInfo()
		this.loadOrders()
	},
	methods: {
		// 加载用户信息
		loadUserInfo() {
			try {
				const userInfo = uni.getStorageSync('userInfo')
				if (userInfo) {
					this.userInfo = JSON.parse(userInfo)
					console.log('加载的用户信息:', this.userInfo) // 调试日志
				} else {
					console.log('未找到用户信息') // 调试日志
				}
			} catch (error) {
				console.error('加载用户信息失败:', error)
			}
		},

		// 加载订单数据
		async loadOrders() {
			try {
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}, 1500)
					return
				}

				// 从本地存储获取用户列表
				const userList = uni.getStorageSync('userList') || []
				const user = userList.find(item => item.uid === JSON.parse(userInfo).uid)
				
				if (user && user.orders) {
					this.orders = user.orders
				} else {
					this.orders = []
				}
			} catch (error) {
				console.error('加载订单失败:', error)
				uni.showToast({
					title: '加载订单失败',
					icon: 'none'
				})
			}
		},

		// 格式化时间
		formatTime(time) {
			if (!time) return ''
			const date = new Date(time)
			return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
		},

		// 获取状态文本
		getStatusText(status) {
			const statusMap = {
				'pending': '待支付',
				'paid': '已支付',
				'shipped': '已发货',
				'completed': '已完成',
				'cancelled': '已取消'
			}
			return statusMap[status] || status
		},

		// 获取状态样式
		getStatusStyle(status) {
			const styleMap = {
				'pending': 'status-pending',
				'paid': 'status-paid',
				'shipped': 'status-shipped',
				'completed': 'status-completed',
				'cancelled': 'status-cancelled'
			}
			return styleMap[status] || ''
		},

		// 显示操作按钮
		showActionButton(order) {
			return order.status === 'pending' || order.status === 'paid'
		},

		// 获取操作按钮文本
		getActionButtonText(order) {
			if (order.status === 'pending') {
				return '去支付'
			} else if (order.status === 'paid') {
				return '确认收货'
			}
			return ''
		},

		// 处理操作按钮点击
		handleActionButtonClick(order) {
			if (order.status === 'pending') {
				this.payOrder(order)
			} else if (order.status === 'paid') {
				this.confirmOrder(order.id)
			}
		},

		// 去支付
		async payOrder(order) {
			try {
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}

				// 从本地存储获取用户列表
				const userList = uni.getStorageSync('userList') || []
				const userIndex = userList.findIndex(item => item.uid === JSON.parse(userInfo).uid)
				
				if (userIndex > -1) {
					// 检查余额
					if (parseFloat(userList[userIndex].balance) < parseFloat(order.totalAmount)) {
						uni.showModal({
							title: '余额不足',
							content: '您的余额不足，是否前往充值？',
							success: (res) => {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/money/money'
									})
								}
							}
						})
						return
					}

					// 更新订单状态
					const orderIndex = userList[userIndex].orders.findIndex(item => item.id === order.id)
					if (orderIndex > -1) {
						userList[userIndex].orders[orderIndex].status = 'paid'
						
						// 扣除余额
						userList[userIndex].balance = (parseFloat(userList[userIndex].balance) - parseFloat(order.totalAmount)).toFixed(2)
						
						// 保存更新后的用户列表
						uni.setStorageSync('userList', userList)
						
						// 更新当前页面的订单数据
						this.orders = userList[userIndex].orders

						uni.showToast({
							title: '支付成功',
							icon: 'success'
						})
					}
				}
			} catch (error) {
				console.error('支付失败:', error)
				uni.showToast({
					title: '支付失败',
					icon: 'none'
				})
			}
		},

		// 确认收货
		async confirmOrder(orderId) {
			try {
				// 获取用户信息
				const userInfo = uni.getStorageSync('userInfo')
				if (!userInfo) {
					uni.showToast({
						title: '请先登录',
						icon: 'none'
					})
					return
				}

				// 从本地存储获取用户列表
				const userList = uni.getStorageSync('userList') || []
				const userIndex = userList.findIndex(item => item.uid === JSON.parse(userInfo).uid)
				
				if (userIndex > -1) {
					// 更新订单状态
					const orderIndex = userList[userIndex].orders.findIndex(order => order.id === orderId)
					if (orderIndex > -1) {
						userList[userIndex].orders[orderIndex].status = 'completed'
						
						// 保存更新后的用户列表
						uni.setStorageSync('userList', userList)
						
						// 更新当前页面的订单数据
						this.orders = userList[userIndex].orders

						uni.showToast({
							title: '确认收货成功',
							icon: 'success'
						})
					}
				}
			} catch (error) {
				console.error('确认收货失败:', error)
				uni.showToast({
					title: '确认收货失败',
					icon: 'none'
				})
			}
		},

		// 删除订单
		async deleteOrder(orderId) {
			try {
				uni.showModal({
					title: '提示',
					content: '确定要删除这个订单吗？',
					success: async (res) => {
						if (res.confirm) {
							// 获取用户信息
							const userInfo = uni.getStorageSync('userInfo')
							if (!userInfo) {
								uni.showToast({
									title: '请先登录',
									icon: 'none'
								})
								return
							}

							// 从本地存储获取用户列表
							const userList = uni.getStorageSync('userList') || []
							const userIndex = userList.findIndex(item => item.uid === JSON.parse(userInfo).uid)
							
							if (userIndex > -1) {
								// 删除订单
								userList[userIndex].orders = userList[userIndex].orders.filter(order => order.id !== orderId)
								
								// 保存更新后的用户列表
								uni.setStorageSync('userList', userList)
								
								// 更新当前页面的订单数据
								this.orders = userList[userIndex].orders

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								})
							}
						}
					}
				})
			} catch (error) {
				console.error('删除订单失败:', error)
				uni.showToast({
					title: '删除订单失败',
					icon: 'none'
				})
			}
		},

		// 去购物
		goShopping() {
			uni.switchTab({
				url: '/pages/index/index'
			})
		},

		// 格式化日期
		formatDate(dateString) {
			try {
				const date = new Date(dateString)
				if (isNaN(date.getTime())) {
					return '日期格式错误'
				}
				return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
			} catch (error) {
				console.error('日期格式化错误:', error)
				return '日期格式错误'
			}
		},

		// 格式化金额
		formatPrice(price) {
			try {
				const num = parseFloat(price)
				if (isNaN(num)) {
					return '¥0.00'
				}
				return `¥${num.toFixed(2)}`
			} catch (error) {
				console.error('金额格式化错误:', error)
				return '¥0.00'
			}
		}
	}
}
</script>

<style>
.order-container {
	min-height: 100vh;
	background-color: #f5f5f5;
	padding: 20rpx;
}

.order-list {
	padding-bottom: 20rpx;
}

.order-item {
	background-color: #fff;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	padding: 20rpx;
}

.order-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-bottom: 20rpx;
	border-bottom: 1rpx solid #eee;
}

.order-id {
	font-size: 24rpx;
	color: #999;
}

.order-status {
	font-size: 24rpx;
	color: #007AFF;
}

.order-content {
	padding: 20rpx 0;
}

.order-product {
	display: flex;
	padding: 20rpx;
	border-bottom: 1rpx solid #eee;
}

.product-image {
	width: 160rpx;
	height: 160rpx;
	border-radius: 8rpx;
	margin-right: 20rpx;
}

.product-info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: space-between;
}

.product-name {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 10rpx;
}

.product-price {
	font-size: 28rpx;
	color: #ff4d4f;
}

.product-quantity {
	font-size: 24rpx;
	color: #999;
}

.order-footer {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding-top: 20rpx;
	border-top: 1rpx solid #eee;
}

.order-time {
	font-size: 28rpx;
	color: #999;
}

.total-amount {
	font-size: 28rpx;
	color: #333;
}

.order-actions {
	display: flex;
	gap: 20rpx;
}

.action-button {
	font-size: 24rpx;
	padding: 10rpx 30rpx;
	border-radius: 30rpx;
	background-color: #fff;
}

.action-button.pay {
	color: #fff;
	background-color: #007AFF;
}

.action-button.review {
	color: #007AFF;
	border: 1rpx solid #007AFF;
}

.action-button.cancel {
	color: #999;
	border: 1rpx solid #999;
}

.action-button.delete {
	background-color: #ff4d4f;
	color: #fff;
	margin-left: 10px;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-top: 200rpx;
}

.empty-image {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 30rpx;
}

.empty-text {
	color: #999;
	font-size: 28rpx;
	margin-bottom: 30rpx;
}

.go-shopping-btn {
	background-color: #007AFF;
	color: #fff;
	padding: 20rpx 60rpx;
	border-radius: 40rpx;
	font-size: 28rpx;
}
</style>
